//
//  HLMatchGoldViewController.m
//  YueYue
//
//  Created by hulu001 on 2023/6/5.
//

#import "HLMatchGoldViewController.h"
#import "HLCamera.h"
#import "HLRtcCallKit.h"
#import "HLMatchRequest.h"
#import "HLCallTool.h"
#import "HLWalletRequest.h"
#import "HLGCDTimerManager.h"

@interface HLMatchGoldViewController ()<HLCameraDelegate>

@property (nonatomic, strong) HLCamera *mCamera;
@property (nonatomic, strong) UIView *previewLayer;
@property (nonatomic, strong) QMUIButton *saveButton;
@property (nonatomic, strong) QMUILabel *titleLabel;
@property (nonatomic, strong) UILabel *detailLabel;
@property (nonatomic, strong) QMUIButton *startButton;
@property (nonatomic, strong) UIImageView *animateView;
@property (nonatomic, assign) BOOL isAnimated;

@end

@implementation HLMatchGoldViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.mCamera = [[HLCamera alloc] initWithCameraPosition:(AVCaptureDevicePositionFront) captureFormat:kCVPixelFormatType_420YpCbCr8BiPlanarFullRange];
    _mCamera.delegate = self;
    [_mCamera startCapture];
    [HLRtcCallKit.sharedInstance setupLocalView:nil];
    [HLRtcCallKit.sharedInstance setupLocalView:_previewLayer];
    HLWalletRequest *walletRequest = [[HLWalletRequest alloc] initWithType:HLWalletTypeBalance params:@{}];
    [walletRequest startWithCompletionBlockWithSuccess:^(__kindof HLWalletRequest * _Nonnull request) {
        if (request.isSuccess){
            [self.saveButton setTitle:[request balance] forState:UIControlStateNormal];
        }
    } failure:nil];
}


- (void)setupNavigationItems
{
    [super setupNavigationItems];
//    UIBarButtonItem *saveItem = [[UIBarButtonItem alloc] initWithCustomView:({
//        QMUIButton *saveButton = [[QMUIButton alloc] init];
//        [saveButton setImage:UIImageMake(@"home_flow_coin") forState:UIControlStateNormal];
//        [saveButton setTitle:@"99" forState:UIControlStateNormal];
//        [saveButton setTitleColor:UIColorWhite forState:UIControlStateNormal];
//        [saveButton.titleLabel setFont:UIFontMake(16)];
//        [saveButton setBackgroundColor:[UIColorBlack colorWithAlphaComponent:0.5]];
//        [saveButton setContentEdgeInsets:UIEdgeInsetsMake(6, 12, 6, 12)];
//        saveButton.imagePosition = QMUIButtonImagePositionLeft;
//        saveButton.spacingBetweenImageAndTitle = 4;
//        saveButton.cornerRadius = 14;
//        self.saveButton = saveButton;
//        saveButton;
//    })];
//
//    self.navigationItem.rightBarButtonItem = saveItem;
}


- (void)initSubviews
{
    [super initSubviews];
    
    self.previewLayer = [[UIView alloc] init];
    [self.view addSubview:_previewLayer];
    [_previewLayer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    QMUIButton *saveButton = [[QMUIButton alloc] init];
    [saveButton setImage:UIImageMake(@"home_flow_coin") forState:UIControlStateNormal];
    [saveButton setTitle:@"99" forState:UIControlStateNormal];
    [saveButton setTitleColor:UIColorWhite forState:UIControlStateNormal];
    [saveButton.titleLabel setFont:UIFontBoldMake(16)];
    [saveButton setBackgroundColor:[UIColorBlack colorWithAlphaComponent:0.5]];
    [saveButton setContentEdgeInsets:UIEdgeInsetsMake(6, 12, 6, 12)];
    saveButton.imagePosition = QMUIButtonImagePositionLeft;
    saveButton.spacingBetweenImageAndTitle = 4;
    saveButton.cornerRadius = 14;
    [self.view addSubview:saveButton];
    [saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(StatusBarHeightConstant + 12);
        make.right.mas_equalTo(-22);
    }];
    self.saveButton = saveButton;
    
    self.titleLabel = [[QMUILabel alloc] qmui_initWithFont:UIFontBoldMake(22) textColor:HLMainColor];
    _titleLabel.text = @"黄金30秒";
    _titleLabel.contentEdgeInsets = UIEdgeInsetsMake(12, 20, 12, 20);
    _titleLabel.backgroundColor = UIColorWhite;
    _titleLabel.layer.masksToBounds = YES;
    _titleLabel.layer.cornerRadius = 9;
    [self.view addSubview:_titleLabel];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.top.mas_equalTo(NavigationContentTopConstant + 24);
    }];
    
    
    self.detailLabel = [[UILabel alloc] qmui_initWithFont:UIFontMediumMake(16) textColor:UIColorWhite];
    _detailLabel.text = @"更多女神在线等你，点击匹配开始心动之旅";
    [self.view addSubview:_detailLabel];
    [_detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.equalTo(_titleLabel.mas_bottom).offset(20);
    }];
    
    self.animateView = [[UIImageView alloc] init];

    _animateView.hidden = YES;
    [self.view addSubview:_animateView];
    [_animateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
    }];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *animatePath = [[NSBundle mainBundle]pathForResource:@"30" ofType:@"gif"];
        UIImage *gif = [UIImage sd_imageWithGIFData:[NSData dataWithContentsOfFile:animatePath]];
        dispatch_sync(dispatch_get_main_queue(), ^{
            self.animateView.image = gif;
        });
    });
    
    self.startButton = [[QMUIButton alloc] init];
    [_startButton setTitle:@"开始匹配" forState:UIControlStateNormal];
    [_startButton setTitle:@"取消匹配" forState:UIControlStateSelected];
    [_startButton setTitleColor:UIColorWhite forState:UIControlStateNormal];
    [_startButton.titleLabel setFont:UIFontMediumMake(16)];
    [_startButton setContentEdgeInsets:UIEdgeInsetsMake(16, 52, 16, 52)];
    [_startButton setBackgroundImage:[UIImage qmui_imageWithColor:HLMainColor] forState:UIControlStateNormal];
    [_startButton setBackgroundImage:[UIImage qmui_imageWithColor:[UIColorBlack colorWithAlphaComponent:0.5]] forState:UIControlStateSelected];
    [_startButton addTarget:self action:@selector(matchAction) forControlEvents:UIControlEventTouchUpInside];
    _startButton.layer.masksToBounds = YES;
    _startButton.cornerRadius = 26;
    [self.view addSubview:_startButton];
    [_startButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.bottom.mas_equalTo(-(SafeAreaInsetsConstantForDeviceWithNotch.bottom + 80));
    }];
    
    
}


#pragma mark ----------FUCameraDelegate-----

- (void)didOutputVideoSampleBuffer:(CMSampleBufferRef)sampleBuffer{
    CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    
    CVPixelBufferLockBaseAddress(pixelBuffer, 0);
    NERtcVideoFrame *videoFrame = [[NERtcVideoFrame alloc] init];
    videoFrame.format = kNERtcVideoFormatNV12;
    videoFrame.width = (uint32_t)CVPixelBufferGetWidth(pixelBuffer);
    videoFrame.height = (uint32_t)CVPixelBufferGetHeight(pixelBuffer);
    videoFrame.timestamp = 0;
    videoFrame.buffer = (void *)pixelBuffer;
    // push给云信
    [[NERtcEngine sharedEngine] pushExternalVideoFrame:videoFrame];
    CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);
}

- (UIImage *)qmui_navigationBarBackgroundImage
{
    return [UIImage qmui_imageWithColor:UIColorClear];
}

- (nullable UIColor *)qmui_navigationBarTintColor
{
    return UIColorWhite;
}

- (nullable UIColor *)qmui_titleViewTintColor
{
    return UIColorWhite;
}

- (BOOL)shouldHideKeyboardWhenTouchInView:(UIView *)view
{
    return YES;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)matchAction
{
    NSString *timerNameUp = @"timerNameUp";
    __block NSInteger countUp = 3;
    
    
    if (self.isAnimated){
        [HLGCDTimerManager cancel:timerNameUp];
        [self matchStateWithAnimated:NO];
        return;
    }
    
    [self matchStateWithAnimated:YES];
    
    [HLGCDTimerManager scheduledTimerWithName:timerNameUp interval:1 delaySecs:0 queue:dispatch_get_main_queue() repeats:YES action:^(NSInteger actionTimes) {
        countUp -= 1;
        if (countUp == 0){
            [HLGCDTimerManager cancel:timerNameUp];
            [self matchRequest];
        }
    }];
    [HLGCDTimerManager start:timerNameUp];

}

- (void)matchStateWithAnimated:(BOOL)isAnimated
{
    self.isAnimated = isAnimated;
    if (isAnimated){
        self.animateView.hidden = NO;
        _detailLabel.text = @"正在快速寻找女神中,请耐心等待…";
        _startButton.selected = YES;
    } else {
        self.animateView.hidden = YES;
        _detailLabel.text = @"更多女神在线等你，点击匹配开始心动之旅";
        _startButton.selected = NO;
    }
}

- (void)matchRequest
{
    MJWeakSelf;
    HLMatchRequest *matchRequest = [[HLMatchRequest alloc] initWithType:HLMatchTypeVideo params:@{}];
    [matchRequest startWithCompletionBlockWithSuccess:^(__kindof HLMatchRequest * _Nonnull request) {
        [self matchStateWithAnimated:NO];
        if (request.isSuccess){
            HLHomeListModel *randomUser = [request fateUser];
            if (randomUser != nil){
                HLUserInfoModel *user = [[HLUserInfoModel alloc] init];
                user.userId = randomUser.userId;
                user.avatar = randomUser.avatar;
                user.nickName = randomUser.nickName;
                user.videoType = HLRtcCallVideoTypeHeartVideo;
                [[HLCallTool shareInstance] matchUser:user OnVC:[QMUIHelper visibleViewController] callback:^(BOOL canMatch) {
                    if (canMatch){
                        [weakSelf.mCamera startCapture];
                        [HLRtcCallKit.sharedInstance setupLocalView:nil];
                        [HLRtcCallKit.sharedInstance setupLocalView:weakSelf.previewLayer];
                        [weakSelf matchAction];
                    }
                }];
            }
        } else {
            [QMUITips showWithText:request.message];
        }
    } failure:^(__kindof HLMatchRequest * _Nonnull request) {
        [self matchStateWithAnimated:NO];
        [QMUITips showWithText:request.message];
    }];
}

@end
